/*******************************************************************************
 * @(#)EMMDatabaseUtils.java 2016年9月22日
 *
 * Copyright 2016 emrubik Group Ltd. All rights reserved.
 * EMRubik PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *******************************************************************************/
package com.inossem.warehousestorage_inossem.manage;

import android.content.Context;

import com.inossem.utils.exception.InossemException;
import com.inossem.utils.log.LogUtils;
import com.inossem.warehousestorage_inossem.R;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DatabaseManage {

    private static final String DATABASEFILENAME = "inossem_database.db";

    private static final String METHODNAME = "upgrade";

    private static List<String> getCreateSql() {

        // 测试表
        String CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, test_id VARCHAR2(256), name VARCHAR2(256))";

        List<String> createSql = new ArrayList<String>();
        createSql.add(CREATE_TABLE_TEST);
        return createSql;
    }

    public static void initDatabase(final Context context) {
        Map<Integer, List<String>> upgradeSql = getUpgradeSql(context);
//        for (Integer key : upgradeSql.keySet()) {
//            LogUtils.logI(context, Constant.LOG_NAME_DATABASE,"版本【 " + (key + 1) + "】,升级SQL语句【 " + upgradeSql.get(key) + "】");
//        }
        int databaseVersion = getNewDatabaseVersion(context);
        LogUtils.logDatabaseI(context, context.getResources().getString(R.string.utils_database_newest_version) + databaseVersion);
        com.inossem.utils.database.DatabaseUtils.initDatabase(context, DATABASEFILENAME, databaseVersion, getCreateSql(),
                upgradeSql, new com.inossem.utils.database.DatabaseUtils.DatabaseResponse() {

                    @Override
                    public void onFailure(int code) {
                        if (com.inossem.utils.database.DatabaseUtils.CREATE_ERROR == code) {
                            LogUtils.logDatabaseE(context, context.getResources().getString(R.string.utils_database_create_error), null);
                        } else if (com.inossem.utils.database.DatabaseUtils.UPGRADE_ERROR == code) {
                            LogUtils.logDatabaseE(context, context.getResources().getString(R.string.utils_database_upgrade_error), null);
                        }
                    }

                    @Override
                    public void onSuccess() {
                        LogUtils.logDatabaseI(context, context.getResources().getString(R.string.utils_database_create_or_upgrade_success));
                    }
                });
    }

    private static int getNewDatabaseVersion(Context context) {
        try {
            List<Integer> indexs;
            Class<?> clazz = DatabaseUpgradeManage.class;
            Method[] methods = clazz.getDeclaredMethods();
            indexs = new ArrayList<>();
            for (int i = 0; i < methods.length; i++) {
                String name = methods[i].getName();
                if (name.startsWith(METHODNAME)) {
                    indexs.add(Integer.parseInt(name.substring(METHODNAME.length(), name.length())));
                }
            }
            return indexs.size();
        } catch (Throwable throwable) {
            LogUtils.logThrowableE(context, "", throwable);
        }
        throw new InossemException("getting database create information error!");
    }

    private static Map<Integer, List<String>> getUpgradeSql(Context context) {
        Map<Integer, List<String>> map;
        try {
            Class<?> clazz = DatabaseUpgradeManage.class;
            Method[] methods = clazz.getDeclaredMethods();
            List<Integer> indexs = new ArrayList<>();
            for (int i = 0; i < methods.length; i++) {
                String name = methods[i].getName();
                if (name.startsWith(METHODNAME)) {
                    indexs.add(Integer.parseInt(name.substring(METHODNAME.length(), name.length())));
                }
            }
            Collections.sort(indexs);
            map = new HashMap<>();
            for (int i = 0; i < indexs.size(); i++) {
                Method m = clazz.getDeclaredMethod(METHODNAME + indexs.get(i));
                List<String> list = (List<String>) m.invoke(clazz.newInstance());
                map.put(i, list);
            }
            return map;
        } catch (Throwable throwable) {
            LogUtils.logThrowableE(context, "", throwable);
        }
        throw new InossemException("getting database upgrade information error!");
    }

}
